package com.server.questionbank.snframe.config.interceptor;

import com.server.questionbank.snframe.util.JWT.JwtTokenProvider;
import jakarta.ws.rs.HttpMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


@Component
public class JwtInterceptor implements HandlerInterceptor {
    public static JwtTokenProvider jwtTokenProvider;

    private static String userId = null;
    private static String currentIp = null;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = jwtTokenProvider.extractTokenFromRequest(request);

        if (token != null) {
            int status = jwtTokenProvider.validateToken(token);
            if (status == 1) {
                String userAccount = jwtTokenProvider.getAccountFromToken(token);
                userId = userAccount;  // 存入 ThreadLocal，整个请求周期可用
                return true;
            }
        }

        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401 未授权
        response.getWriter().write("Unauthorized: Invalid or missing token");
        return false;
    }

    // 设置当前请求的用户 ID
    public static void setCurrentUser(HttpServletRequest request) {
        String token = jwtTokenProvider.extractTokenFromRequest(request);
        if (token != null) {
            int status = jwtTokenProvider.validateToken(token);
            if (status == 1) {
                String userAccount = jwtTokenProvider.getAccountFromToken(token);
                userId = userAccount;
            }
        } else {
            userId = null;
        }
    }

    // 获取当前请求的用户 ID
    public static String getCurrentUser() {
//        return userThreadLocal.get();
        return userId;
    }

    // 设置当前请求的 IP
    public static void setCurrentIp(String _currentIp) {
        currentIp = _currentIp;
    }

    // 获取当前请求的 IP
    public static String getCurrentIp() {
        return currentIp;
    }

    // 请求结束后清除 ThreadLocal，防止内存泄漏
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        userId = null;
        currentIp = null;
    }
}
